//
//  HYImageView.m
//  HaiYue
//
//  Created by skyline on 2017/12/19.
//  Copyright © 2017年 skyline. All rights reserved.
//

#import "HYImageView.h"
@interface HYImageView ()
@end
@implementation HYImageView

- (instancetype)initWithImage:(UIImage *)image cornerRadius:(CGFloat)radius
{
    self = [super initWithImage:image];
    if (self)
    {
        self.autoSize_imageURL = NO;
        self.layer.masksToBounds = YES;
        self.layer.cornerRadius = radius;
        self.layer.bounds = CGRectMake(0, 0, radius * 2, radius * 2);
    }
    return self;
}

- (instancetype)initWithCornerRadius:(CGFloat )radius
{
    self = [super init];
    if (self)
    {
        self.autoSize_imageURL = NO;
        self.layer.masksToBounds = YES;
        self.layer.cornerRadius = radius;
        self.layer.bounds = CGRectMake(0, 0, radius * 2, radius * 2);
    }
    return self;
}

- (void)setImageURL:(NSString *)imageURL
{
    
    if (_imageURL != imageURL)
    {
        _imageURL = imageURL;
//        NSLog(@" ========_________%@ ??   %@",self, _imageURL);
        if (imageURL)
        {
//            self.image = [UIImage imageWithURL:self.imageURL];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imageURL]];

                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"----- imageurl --- %@",_imageURL);

                    self.image = [UIImage imageWithData:data];

                    if (self.image && self.superview && self.autoSize_imageURL)
                    {
                        CGFloat times = MIN(self.superview.bounds.size.height /self.image.size.height, self.superview.bounds.size.width / self.image.size.width);

                        [self mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.size.mas_offset(CGSizeMake(self.image.size.width * times, self.image.size.height * times));
                        }];
                    }
                });
            });
        }
        else
        {
//            self.image = nil;
        }
    }
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
